package cn.studyjams.s1.contest.autohello;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.annotation.VisibleForTesting;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import java.util.Calendar;

import cn.studyjams.s1.contest.autohello.model.RepeatMode;
import cn.studyjams.s1.contest.autohello.receiver.NotificationReceiver;

/**
 * Created by liuyang
 * on 2016/10/5.
 */

public class BaseActivity extends AppCompatActivity {

    private static final String TAG = "BaseActivity";
    SharedPreferences sharedPref;

    @VisibleForTesting
    public ProgressDialog mProgressDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
        Log.d(TAG, sharedPref.getBoolean("notifications_new_message", true) + "");
    }

    public void showProgressDialog(String content) {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setCancelable(false);
            mProgressDialog.setMessage(content);
            mProgressDialog.setIndeterminate(true);
        }

        mProgressDialog.show();
    }

    public void hideProgressDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }

    @Override
    protected void onStop() {
        Log.d(TAG, "onStop");
        super.onStop();
        hideProgressDialog();
    }

    public Calendar getNextExecuteTime(Calendar calendar, RepeatMode repeatMode) {
        int repeatType = repeatMode.getRepeatType();
        int howOften = repeatMode.getHowOften();

        switch (repeatType) {
            case 0:
                // dose not repeat. plus one day
                calendar.add(Calendar.DATE, 1);
                break;
            case 1:
                // repeat daily howOften
                calendar.add(Calendar.DATE, howOften);
                break;
            case 2:
                // repeat weekly howOften, whichWeeks;
                int currentDayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
                String weeksStr = repeatMode.getWhichWeeks();
                String[] whichWeeks = weeksStr.substring(1, weeksStr.length() - 1).split(", ");

                int nextIndex;
                // 明天是不是一个新的星期
                if (currentDayOfWeek < 7) {
                    nextIndex = currentDayOfWeek;
                } else {
                    // currentDayOfWeek == 7
                    nextIndex = 0;
                }

                int plusDays = 1;
                while(whichWeeks[nextIndex].equals("false")) {
                    nextIndex = ++nextIndex % 7;
                    plusDays++;
                }

                calendar.add(Calendar.DATE, (howOften - 1) * 7 + plusDays);
                break;
            case 3:
                // repeat monthly howOften, SameDayOrSameWeekOfTheMonth;
                int sameDayOrSameWeek = repeatMode.getSameDayOrSameWeekOfTheMonth();
                if (sameDayOrSameWeek == 0) {
                    calendar.add(Calendar.MONTH, howOften);
                } else if (sameDayOrSameWeek == 1) {
                    // 获取当前日期是星期几，和是本月的第几个星期几
                    int week = calendar.get(Calendar.DAY_OF_WEEK);
                    int weekIndex = calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH);

                    calendar.add(Calendar.MONTH, howOften);
                    calendar.set(Calendar.DAY_OF_WEEK, week);
                    calendar.set(Calendar.DAY_OF_WEEK_IN_MONTH, weekIndex);
                }
                break;
            case 4:
                // repeat yearly howOften;
                calendar.add(Calendar.YEAR, howOften);
                break;
            default:
                break;
        }
        return calendar;
    }

    public void setAlarm(String eventId, int requestCode, long triggerAtMillis) {
        AlarmManager alarmMgr = (AlarmManager) getSystemService(ALARM_SERVICE);

        Intent intent = new Intent(getApplicationContext(), NotificationReceiver.class);
        intent.putExtra("event_id", eventId);

        PendingIntent alarmIntent = PendingIntent.getBroadcast(
                getApplicationContext(),
                requestCode,
                intent,
                PendingIntent.FLAG_UPDATE_CURRENT
        );

        alarmMgr.set(
                AlarmManager.RTC,
                triggerAtMillis,
                alarmIntent
        );
    }

    public void cancelAlarm(String eventId, int requestCode) {
        AlarmManager alarmMgr = (AlarmManager) getSystemService(ALARM_SERVICE);

        Intent intent = new Intent(getApplicationContext(), NotificationReceiver.class);
        intent.putExtra("event_id", eventId);

        PendingIntent alarmIntent = PendingIntent.getBroadcast(
                getApplicationContext(),
                requestCode,
                intent,
                PendingIntent.FLAG_UPDATE_CURRENT
        );

        alarmMgr.cancel(alarmIntent);
    }

    public void hideSoftKeyboard(View v) {
        InputMethodManager inputMethodMgr = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        inputMethodMgr.hideSoftInputFromWindow(v.getWindowToken(), 0);
    }
}
